package com.yonyou.brigade.order_center.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.yonyou.brigade.basic_init.model.BriChannel;
import com.yonyou.brigade.basic_init.service.IBriChannelService;
import com.yonyou.brigade.order_center.model.CLYHConfig;
import com.yonyou.brigade.order_center.model.ExpenseStatus;
import com.yonyou.brigade.order_center.model.ThirdResult;
import com.yonyou.brigade.order_center.service.IBriOrderService;
import com.yonyou.brigade.order_center.service.IThirdOrderService;
import com.yonyou.brigade.order_center.util.YHUtils;
import com.yonyou.brigade.util.operateutil.JsonUtils;
import com.yonyou.brigade.util.resultutil.HttpSendUtils;
import com.yonyou.framework.util.StringUtil;
import com.yonyou.ybzboot.starter.common.exception.BusinessException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.*;

@Service
public class ThirdOrderServiceImpl implements IThirdOrderService {

    Logger logger = LoggerFactory.getLogger(this.getClass());

    @Value("${yihao.url.reimburseInfoBackfill}")
    private String reimburseInfoBackfill;

    @Autowired
    private IBriChannelService briChannelService;

    @Autowired
    private IBriOrderService briOrderService;

    @Autowired
    private YHUtils yHUtils;

    @Override
    public void clyhOrdersStateBackFill(String tenant, JSONArray fillBackCLYHParam) {
        logger.info("开始回传差旅壹号报销状态");
        for (int i = 0; i < fillBackCLYHParam.size(); i++) {
            JSONObject param = fillBackCLYHParam.getJSONObject(i);
            String orderNo = param.getString("orderNo");
            String orderType = param.getString("orderType");
            String bxStatus = param.getString("bxStatus");
            try {
                logger.info(tenant + ":" + orderNo + ":" + orderType + ":" + bxStatus);
                clyhOrderStateBackFill(tenant, param);
            }catch (Exception e){
                logger.error("回传差旅壹号报销状态异常");
            }
        }
    }

    @Override
    public ThirdResult clyhOrderStateBackFill(String tenant, JSONObject param) {
        String orderNo = param.getString("orderNo");
        String orderType = param.getString("orderType");
        JSONObject briOrderDetail = briOrderService.getBriOrderDetail(tenant, orderNo, orderType);
        if (briOrderDetail == null){
            throw new BusinessException("订单号错误，未找到该订单：" + orderNo);
        }
        if (!"clyh".equalsIgnoreCase(briOrderDetail.getString("fromType"))){
            return new ThirdResult(false, orderNo +"不是差旅壹号订单");
        }
        Map<String, Object> requestParam = assembleClyhRequest(tenant, param, orderNo, briOrderDetail);
        //同步订单的报销状态，返回结果 0：失败 1：成功
        logger.info("差旅壹号同步报销状态>>> url:" + reimburseInfoBackfill +"参数："+ JSON.toJSONString(requestParam));
        String result = HttpSendUtils.sendPost(reimburseInfoBackfill, JSON.toJSONString(requestParam));
        logger.info("差旅壹号同步报销状态结果：" + result);
        return getClyhResult(result);
    }

    private ThirdResult getClyhResult(String result) {
        if (StringUtil.isNotEmpty(result) && JsonUtils.isJSONObject(result)) {
            JSONObject resultJSON = JSONObject.parseObject(result);
            if (resultJSON.getBoolean("successful")) {
                JSONArray dataArray = resultJSON.getJSONArray("data");
                if (!CollectionUtils.isEmpty(dataArray)) {
                    JSONObject dataJSON = dataArray.getJSONObject(0);
                    if (dataJSON.getBoolean("success")) {
                        logger.info("同步报销状态成功 keyId：" + dataJSON.get("dataInfo"));
                        return new ThirdResult(true,"同步报销状态成功");
                    } else {
                        logger.error("同步报销状态失败 keyId：" + dataJSON.get("dataInfo") + ",msg:" + dataJSON.getString("msg"));
                        return new ThirdResult(false, "同步报销状态失败");
                    }
                } else {
                    logger.error("同步报销状态失败，差旅壹号接口返回数据为空");
                    return new ThirdResult(false, "同步报销状态失败，差旅壹号接口返回数据为空");
                }
            } else {
                logger.error("同步报销状态失败，差旅壹号接口返回失败");
                return new ThirdResult(false, "同步报销状态失败，差旅壹号接口返回失败");
            }
        } else {
            logger.error("同步报销状态失败，差旅壹号返回值有误");
            return new ThirdResult(false, "同步报销状态失败，差旅壹号返回值有误");
        }
    }

    private Map<String, Object> assembleClyhRequest(String tenant, JSONObject param, String orderNo, JSONObject briOrderDetail) {
        Wrapper<BriChannel> wrapper = new EntityWrapper<>();
        wrapper.eq(BriChannel.ID, briOrderDetail.getString("channelId"));
        BriChannel briChannel = briChannelService.selectOne(wrapper);
        CLYHConfig channelConfig = JSONObject.parseObject(briChannel.getConfig(), CLYHConfig.class);
        JSONObject config = convertToJSON(channelConfig);
        ExpenseStatus expenseStatus = param.getJSONObject("expenseStatus") != null ? JSONObject.parseObject(JSON.toJSONString(param.getJSONObject("expenseStatus")), ExpenseStatus.class) : null;
        //请求标识
        String requestId = orderNo + System.currentTimeMillis();
        //获取token
        String token = yHUtils.getToken(tenant, requestId, config);
        //拼装请求数据
        JSONObject reimburseStateRequest = new JSONObject();
        String keyId = StringUtil.isNotEmpty(briOrderDetail.getString("relateOtherId")) ? briOrderDetail.getString("relateOtherId") : briOrderDetail.getString("relateOtherID");
        logger.info("keyID为" + keyId);
        JSONArray reimburseStateRequests = new JSONArray();
        Map<String,Object> requestParam = new HashMap<>();
        Set<String> dataInfo = new HashSet<>();
        dataInfo.add(keyId);
        reimburseStateRequest.put("condition", "KeyId");
        reimburseStateRequest.put("dataInfo", dataInfo);
        reimburseStateRequest.put("outBusinessRemark", expenseStatus.getFinOrgName());
        reimburseStateRequest.put("outBusinessNo", expenseStatus.getBillnum());
        reimburseStateRequest.put("reimburseDate", expenseStatus.getVoucherDateTime());
        reimburseStateRequest.put("reimburseState", "2".equals(expenseStatus.getBx_state()) ? "1" : "0");
        reimburseStateRequest.put("reimburseStateName", getReimburseStateName(expenseStatus.getBx_state()));
        reimburseStateRequest.put("checkBatchNo", expenseStatus.getVoucherTypeName());
        reimburseStateRequest.put("varcherNo", expenseStatus.getVoucherNo());
        reimburseStateRequests.add(reimburseStateRequest);
        requestParam.put("access_token",token);
        requestParam.put("data",reimburseStateRequests);
        requestParam.put("requestid",requestId);
        return requestParam;
    }

    /**
     * 获取报销状态名称
     * @param bxStatus
     * @return
     */
    private String getReimburseStateName(String bxStatus){
        switch (bxStatus){
            case "0":
                return "未报销";
            case "1":
                return "报销中";
            case "2":
                return  "已报销";
        }
        return "";
    }

    private JSONObject convertToJSON(CLYHConfig channelConfig) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("version", channelConfig.getVersion());
        jsonObject.put("appid", channelConfig.getAppid());
        jsonObject.put("appsecret", channelConfig.getAppsecret());
        return jsonObject;
    }
}
